<template>
  <wd-drop-menu>
    <!-- <wd-drop-menu-item v-model="lhValue" :options="lhOptions" value-key="adcode" label-key="name" /> -->
    <wd-drop-menu-item
      v-model="townState.value"
      :options="townState.options"
      value-key="orgCode"
      label-key="title"
    />
    <wd-drop-menu-item
      v-model="hallState.value"
      :options="hallState.options"
      value-key="id"
      label-key="name"
    />
  </wd-drop-menu>
</template>

<script setup>
import { DEFAULT_CITY_CODE, DEFAULT_COUNTRY_CENTER, DEFAULT_COUNTRY_CODE } from '@/configs/constant'
import allAreas from '@/static/zjGeo.json'
import HallApi from '@/service/hall'
import { reactive } from 'vue'

const LH_DEPART_CODE = '1837020020443426818'

const lhOptions = [{ name: '临海市', adcode: DEFAULT_CITY_CODE }]
const lhValue = ref(DEFAULT_CITY_CODE)

const townState = reactive({
  value: '',
  options: [],
})

const getLhDepartTree = async () => {
  const params = {
    pid: LH_DEPART_CODE,
    primaryKey: 'orgCode',
  }
  const { code, result } = await HallApi.getDepartTree(params)
  if (result?.length > 0) {
    townState.options = result
    townState.value = townState.options[0]?.orgCode
    getAllHallList()
  } else {
    townState.options = []
  }
}
getLhDepartTree()

watch(
  () => townState.value,
  () => {
    getHallList()
  },
)

const getHallList = async () => {
  const params = {
    orgCode: townState.value,
  }
  const { code, result } = await HallApi.getHallList(params)
  if (result?.length > 0) {
    hallState.options = result
  }
}

const hallState = reactive({
  value: '',
  options: [],
})

const cityValue = ref(DEFAULT_CITY_CODE)
const countryValue = ref(DEFAULT_COUNTRY_CODE)
const currentCountryCenter = ref(DEFAULT_COUNTRY_CENTER)

const areaData = ref(allAreas)
const cityOptions = ref(allAreas)
// const countryOptions = ref([])

const countryOptions = computed(() => {
  const countryOpts = cityOptions.value.find((item) => item.adcode === cityValue.value)?.districts
  return countryOpts || []
})

const emits = defineEmits(['change'])

watch(
  () => cityValue.value,
  (val) => {
    const { adcode, center } = countryOptions.value[0]
    countryValue.value = adcode
    currentCountryCenter.value = center
    emits('change', { city: val, country: adcode, center })
  },
)

const changeCountry = ({ selectedItem }) => {
  const { adcode, center } = selectedItem
  emits('change', { city: cityValue.value, country: adcode, center })
}
</script>
